/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *reverseKGroup(ListNode *head, int k) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
		if (head == NULL || k == 1) {
			return head;
		}
		ListNode* pre = NULL;
		ListNode* cur = head;
		ListNode* last = NULL;
		ListNode* first = NULL;
		ListNode* next = NULL;

		while (cur) {
			last = cur;
			for (int i = 0; last && i < k - 1; ++i) {
				last = last->next;
			}
			if (last == NULL) {
				break;
			}

			first = cur;
			next = cur->next;
			while (cur != last) {
				ListNode* t = next->next;
				next->next = cur;
				cur = next;
				next = t;
			}
			if (pre == NULL) {
				head = last;
			} else {
				pre->next = last;
			}

			first->next = next;
			pre = first;
			cur = pre->next;
		}
		return head;

    }
};